package com.simon.hse.activity.education;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.pdf.PdfRenderer;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.http.ApiConstanse;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.LearnTimeOutput;
import com.simon.hse.http.entity.OnLineLearnDetailOutput;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;

/**
 * 学习内容
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_learning_content)
public class LearningContentActivity extends BaseActivity {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.tv_learn_content_time)
    TextView mTv_learn_content_time;

    @ViewInject(R.id.tv_pdf_empty)
    TextView mTv_pdf_empty;

    @ViewInject(R.id.vp_pdf)
    ViewPager mVp_pdf;

    private String id;
    private String url;
    private boolean show_time;// 是否展示计时

    private String FILE_PATH = Environment.getExternalStoragePublicDirectory("Download").getAbsolutePath();
    private String FILE_NAME = "learning.pdf";

    private ParcelFileDescriptor mDescriptor;
    private PdfRenderer mRenderer;
    private Handler mHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mHandler.removeMessages(0);
                    initAddLearnTime();
                    mHander.sendEmptyMessageDelayed(0, 60000);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        if (bundle == null)
            return;

        id = bundle.getString("ID");
        url = bundle.getString("URL");
        show_time = bundle.getBoolean("SHOW_TIME");
        if (show_time) {
            initLearnTime();
        } else {
            mTv_learn_content_time.setVisibility(View.GONE);
        }
        downFile(ApiConstanse.BASE_URL + ApiConstanse.DOWNLOAD_FILE + "?id=" + id);
//        initLearningDetail();
    }

    @Event(value = {R.id.iv_common_left, R.id.iv_common_right})
    private void back(View view) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.iv_common_left:
                finish();
                break;
            case R.id.iv_common_right:
                intent.setClass(LearningContentActivity.this, LearningExaminationActivity.class);
                bundle.putString("TITLE", "模拟考试");
                bundle.putString("ID", id);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
        }
    }

    /**
     * 获取累计学习时间
     */
    private void initLearnTime() {
        Call<String> call = HttpManager.getInstance().requestService().COURSE_HOURS(id);
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                LearnTimeOutput learnTimeOutput = new Gson().fromJson(result, LearnTimeOutput.class);
                if (learnTimeOutput.getResult().equals("Success")) {
                    mTv_learn_content_time.setText("累计学习时长：" + learnTimeOutput.getData().getCourseHours() + "分钟");
                    mHander.sendEmptyMessageDelayed(0, 60000);
                } else {
                    ToastUtils.getInstance().showShortToastBottom(learnTimeOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 增加-累计学习时间
     */
    private void initAddLearnTime() {
        Call<String> call = HttpManager.getInstance().requestService().TOTAL_MINUTE(id);
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                LearnTimeOutput learnTimeOutput = new Gson().fromJson(result, LearnTimeOutput.class);
                if (learnTimeOutput.getResult().equals("Success")) {
                    mTv_learn_content_time.setText("累计学习时长：" + learnTimeOutput.getData().getCourseHours() + "分钟");
                } else {
                    ToastUtils.getInstance().showShortToastBottom(learnTimeOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 在线学习详情
     */
    private void initLearningDetail() {
        Call<String> call = HttpManager.getInstance().requestService().ONLINE_STUDY_DETAIL(id);
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                OnLineLearnDetailOutput learnDetailOutput = new Gson().fromJson(result, OnLineLearnDetailOutput.class);
                if (learnDetailOutput.getResult().equals("Success")) {
                    final OnLineLearnDetailOutput.DataBean dataBean = learnDetailOutput.getData();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTv_common_title.setText(dataBean.getCoursewareName());
                            mTv_pdf_empty.setText("数据加载中，请稍后...");
                            // downFile(ApiConstanse.baseUrl+ApiConstanse.DOWNLOAD_FILE+"?id="+dataBean.getCourseAttachment());
                            downFile("http://39.152.6.44:8052/api/File/DownLoad?id=e783970d-1477-44a5-d419-08d73b206bc5");
                        }
                    });
                } else {
                    ToastUtils.getInstance().showShortToastBottom(learnDetailOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    /**
     * 下载apk文件
     *
     * @param url
     */
    public void downFile(final String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
                // 下载失败
                mTv_pdf_empty.setText("数据加载失败，请返回重新尝试！");
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                InputStream is = null;//输入流
                FileOutputStream fos = null;//输出流
                try {
                    is = response.body().byteStream();//获取输入流
                    File file = null;
                    if (is != null) {
                        file = new File(FILE_PATH, FILE_NAME);// 设置路径
                        fos = new FileOutputStream(file);

                        int len = 0;
                        byte[] buf = new byte[1024];
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                        }
                    }
                    fos.flush();
                    // 下载完成
                    if (fos != null) {
                        fos.close();
                        openRender();
                    }
                } catch (Exception e) {
                    mTv_pdf_empty.setText("数据加载失败，请返回重新尝试！");
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    /**
     * 开启pdf
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void openRender() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = new File(FILE_PATH, FILE_NAME);
                    mDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);

                    //初始化PdfRender
                    if (mDescriptor != null) {
                        mRenderer = new PdfRenderer(mDescriptor);
                    }
                    //初始化ViewPager的适配器并绑定
                    MyAdapter adapter = new MyAdapter();
                    mVp_pdf.setAdapter(adapter);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * vp适配器
     */
    class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mRenderer.getPageCount();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = LayoutInflater.from(LearningContentActivity.this).inflate(R.layout.layout_item_vp_pdf, null);
            ImageView iv_pdf = (ImageView) view.findViewById(R.id.iv_pdf);
            // pvPdf.enable();
            if (getCount() <= position) {
                return view;
            }

            PdfRenderer.Page currentPage = mRenderer.openPage(position);
            Bitmap bitmap = Bitmap.createBitmap(1080, 1760, Bitmap.Config
                    .ARGB_8888);
            currentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
            iv_pdf.setImageBitmap(bitmap);
            // 关闭当前Page对象
            currentPage.close();
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // 销毁需要销毁的视图
            container.removeView((View) object);
        }
    }

    @Override
    protected void onDestroy() {
        // 销毁页面的时候释放资源
        try {
            mRenderer.close();
            mDescriptor.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        mHander.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

}
